<template>

    <Form ref="formValidate" :model="formValidate" :label-width="80" :rules="ruleValidate" style="position: relative;"> 
        <FormItem label="入学年月">
            <Col span="19">
            <DatePicker transfer v-model="lookstart_year" type="month" @on-change="getstart_year" placeholder="入学年月" style="width: 100%"></DatePicker>
            </Col>
        </FormItem>  
        <FormItem label="入学方式" prop="admission_method_id">
            <Select v-model="formValidate.admission_method_id" style="width:80%" transfer clearable>
                <Option  v-for="item in listDictionary.admission_methods" :value="item.dictionary_id" :key="item.dictionary_id">{{item.dictionary_name.zh?item.dictionary_name.zh:item.dictionary_name.mn}}</Option>            
            </Select>
        </FormItem>

        <FormItem v-if="typeother=='eclass'" label="班级" prop="eclass_id">
            <Select v-model="formValidate.eclass_id" transfer>
                <Option  v-for="item in listBasic.grade" :value="item.value" :key="item.value">{{item.label}}</Option>            
            </Select>
        </FormItem>
        <FormItem v-else label="班级">
            <Cascader v-model="formValidate.eclass_id" transfer :data="listBasic.grade" :load-data="loadData"></Cascader>
        </FormItem>
        <FormItem label="学生来源" prop="student_from_id">
            <Select v-model="formValidate.student_from_id" style="width:80%" transfer clearable>
                <Option  v-for="item in listDictionary.student_from" :value="item.dictionary_id" :key="item.dictionary_id">{{item.dictionary_name.zh?item.dictionary_name.zh:item.dictionary_name.mn}}</Option>            
            </Select>
        </FormItem>
        <FormItem label="就读方式" prop="way_to_study">
            <Select v-model="formValidate.way_to_study" style="width:80%" transfer clearable>
                <Option :value="0" :key="0">走读</Option>  
                <Option :value="1" :key="1">寄宿</Option>            
            </Select>
        </FormItem>
        <FormItem label="上传文件" v-if="formValidate.way_to_study=='0'">
            <Upload :action="picurl" name="file" :headers="headers" :on-success="upload_success">
                <Button type="ghost" icon="ios-cloud-upload-outline">上传文件</Button>
            </Upload>
            <a v-if="way_to_annex" :href="way_to_annex" download="附件">查看附件</a>
        </FormItem>

        <FormItem style="width:90%;">
            <Button type="primary" @click="handleSubmit('formValidate')">保存</Button>
        </FormItem>                       
        <div style="clear:both"></div>
        <Spin size="large" fix v-if="spinShow"></Spin>                     
    </Form> 
</template>
<script>
export default {
    props: {
        infoOld: {
            type: [Boolean,Number,Object,Array],
            default: false
        },
        typeother: {
            type: [Boolean,String],
            default: false
        }
    },
    data() {
        const validateMembershipNumber = (rule, value, callback) => {
            setTimeout(() => {
                if (!value) {
                    return callback(new Error('请填写学籍辅号'));
                }else if (value.length<12) {
                    return callback(new Error('学籍辅号12位'));
                }if (!Number.isInteger(value)) {
                    callback(new Error('请输入数字值'));
                }else{
                    callback();
                }
            }, 1000);
        };
        return {
            infoUrl:`api/student/v1/studentlearnstatus/lists/${this.infoOld.learnstatus?this.infoOld.learnstatus.student_learnstatus_id : ''}`,//请求单条数据
            saveUrl:'',//保存接口
            saveType:null,//保存方式
            
            // 数据字典获取数据  血型
            listDictionary:{
                admission_methods:[],
                student_from:[]
            },
            spinShow:false,


            lookstart_year:null,//显示入学年份
            picurl:this.$project.axios.baseUrl+'/api/user/v1/upload',
            way_to_annex:null,//附件的显示   
            headers: {
                'Authorization': 'Bearer '+((localStorage.token)?(localStorage.token):'')
            },

            // 学籍基本信息  年级  班级
            listBasic:{
                grade:[],//年级
            },     
            
            infoOldObj:null,// 个人辅助数据

            // 个人辅助信息
            formValidate: {
                membership_number: null,//学籍辅号
                class_code:null,//班内学号
                student_from_id:null,//学生来源
                eclass_id:this.typeother=='eclass' ? null : [],//班级id
                start_year:null,//入学年份
                admission_method_id:null,//入学方式
                way_to_study:null,//就读方式
                way_to_annex:null,//文件
                user_id:this.infoOld.user_id,            
            },
            ruleValidate: {
                student_from_id: [
                    { type:'number',required: true, message: '请选择学生来源', trigger: 'change' }
                ],
                admission_method_id: [
                    { type:'number',required: true, message: '请选择入学方式', trigger: 'change' }
                ],
                eclass_id: [
                    { type:'number',required: true, message: '请选择班级', trigger: 'change' }
                ],
                way_to_study: [
                    { type:'number',required: true, message: '请选择就读方式', trigger: 'change' }
                ],
            },
        }
    },
    methods: {
        
        /************************************************************
         * 
         * 单条获取个人辅助信息
         * 
         ************************************************************/
        infoData(){
            this.spinShow=true
            this.$http.get(this.infoUrl).then(val=>{ 
                this.infoOldObj = JSON.parse(JSON.stringify(val.data))
                this.formValidate.student_from_id = this.infoOldObj.student_from_id ==null ? '' : parseInt(this.infoOldObj.student_from_id)//用于默认选的 学生来源
                this.formValidate.admission_method_id =  this.infoOldObj.admission_method_id ==null ? '' : parseInt(this.infoOldObj.admission_method_id)//用于默认选的 入学方式
                this.formValidate.way_to_study =  this.infoOldObj.way_to_study ==null ? '' : parseInt(this.infoOldObj.way_to_study)//用于默认选的 就读方式
                this.formValidate.membership_number = this.infoOldObj.membership_number// 学籍辅号
                this.formValidate.class_code = this.infoOldObj.class_code// 班内学号
                this.lookstart_year = this.infoOldObj.start_year// 入学年份
                this.getstart_year(this.infoOldObj.start_year)//用于入学年份提交
                this.way_to_annex=this.infoOldObj.way_to_annex
                if(this.listBasic.grade.length!=0){
                    let ss = this.listBasic.grade.find(i => {return i.id == this.infoOldObj.eclass.arrives_id});
                    this.formValidate.eclass_id =this.typeother=='eclass' ? this.infoOldObj.eclass.eclass_id : [ss.value,this.infoOldObj.eclass.eclass_id]//用于默认选的 班级
                }
                this.spinShow=false
            }).catch(err=>{
                console.log(err);
                if(err.code && err.code==422) {
                    this.$Message.error(err.message);
                }
                this.spinShow=false
            })
        },
        
        /************************************************************
         * 
         * 个人辅助信息提交
         * 
         ************************************************************/
        handleSubmit (name) {
            if(this.formValidate.way_to_study=='0' && !this.formValidate.way_to_annex && !this.way_to_annex){
                this.$Message.error("请上传附件!");
                return
            }
            if(this.formValidate.eclass_id.length==0 && this.typeother!='eclass'){
                this.$Message.error("请选择班级!");
                return
            }
            this.$refs[name].validate((valid) => {
                if (valid) {   
                    this.spinShow=true   
                    let form = JSON.parse(JSON.stringify(this.formValidate))
                    if(this.typeother!='eclass'){
                        form.eclass_id = form.eclass_id[1]
                    }
                    this.saveType(this.saveUrl,form).then(val=>{
                        this.$Message.success(val.message);
                        this.$emit('expandback',true)
                        this.spinShow=false
                    }).catch(err=>{
                        console.log(err);
                        if(err.code && err.code==422) {
                            this.$Message.error(err.message);
                        }
                        this.spinShow=false
                    })
                } else {
                    this.$Message.error("表单验证失败!");
                }    
            })
        },
        
        /************************************************************
         * 
         * 提交处理日期格式
         * 
         ************************************************************/
        getstart_year(start){
          this.formValidate.start_year = start;
        },   
        
        
        /************************************************************
         * 
         * 上传附件
         * 
         ************************************************************/
        upload_success(str){
            this.formValidate.way_to_annex=str.data.id
        }, 

        /************************************************************
         * 
         * 数据字典获取数据
         * 
         ************************************************************/
        listDictionaryFun(){
            this.spinShow=true
            this.$http.get('api/dictionary/v1/dictionary/pidquerys?admission_methods&student_from')
            .then((response) => {
                this.listDictionary=response.data
                this.spinShow=false
            })
            .catch(err=>{
                console.log(err);
                if(err.code && err.code==422) {
                    this.$Message.error(err.message);
                }
                this.spinShow=false
            })
        },

        /************************************************************
         * 
         * 获取年级
         * 
         ************************************************************/
        gradelist() {
            //年级
            if(this.typeother=='eclass'){
                this.spinShow=true
                this.$http.get('api/safety/v1/certifications/classlist')
                .then((response) => {
                    this.listBasic.grade = response.data.map(item => {
                        let arr = {
                                value: item.eclass_id,
                                label: item.eclass_name.zh?item.eclass_name.zh:item.eclass_name.mn,
                            }
                        return arr
                    })
                    if(this.infoOld.learnstatus){
                        this.infoData()
                    }
                    this.spinShow=false
                })
                .catch(err=>{
                    console.log(err);
                    if(err.code && err.code==422) {
                        this.$Message.error(err.message);
                    }
                    this.spinShow=false
                }) 
            }else{
                this.spinShow=true
                this.$http.get('api/base/v1/get/all/arrives')
                .then((response) => {
                    if(this.infoOld.learnstatus){
                        this.infoData()
                    }
                    let arr = response.data.filter(item => item.grade)
                    this.listBasic.grade = arr.map(item => {
                        let arr = {
                                value: item.grade.id,
                                id: item.id,
                                label: item.name.zh+'('+item.grade.grade_name.zh+')',
                                children: [],
                                loading: false
                            }
                        return arr
                    })
                    this.spinShow=false
                })
                .catch(err=>{
                    console.log(err);
                    if(err.code && err.code==422) {
                        this.$Message.error(err.message);
                    }
                    this.spinShow=false
                }) 

            }
        },

        /************************************************************
         * 
         * 异步加载数据
         * 
         ************************************************************/ 
        loadData(item, callback) {
            item.loading = true;
            this.$http.get('api/eclass/v1/eclass/grade_eclass?grade_id='+item.value)
            .then(response=>{    
                setTimeout(() => {
                    item.children = response.data.map((item1)=>{
                        let obj = {
                            value : item1.eclass_id,
                            label : item1.eclass_name.zh?item1.eclass_name.zh:item1.eclass_name.mn,
                        }
                        return obj
                    })
                    item.loading = false;
                    callback();
                }, 1000);       
            })
            .catch(err=>{
                console.log(err);
                if(err.code && err.code==422) {
                    this.$Message.error(err.message);
                }  
                item.loading = false;                       
            })
                
        },

    },
    created() {
        this.gradelist()
        this.listDictionaryFun()
        
        if(this.infoOld.learnstatus){
            // 如果有值 就是修改

            this.saveUrl=`api/student/v1/studentlearnstatus/update/${this.infoOld.learnstatus.student_learnstatus_id}`
            this.saveType=this.$http.put
        }else{
            // 如果没有有值 就是添加  
            this.saveUrl='api/student/v1/studentlearnstatus/create'
            this.saveType=this.$http.post
        }
        
    },
    watch:{
        infoOld: {
            handler (val) {
                if(this.infoOld.learnstatus){
                    // 如果有值 就是修改
                    // this.infoUrl=`api/student/v1/studentlearnstatus/lists/${this.infoOld.learnstatus?this.infoOld.learnstatus.student_learnstatus_id : ''}`,//请求单条数据
                    // this.gradelist()
                    this.saveUrl=`api/student/v1/studentlearnstatus/update/${this.infoOld.learnstatus.student_learnstatus_id}`
                    this.saveType=this.$http.put
                }else{
                    // 如果没有有值 就是添加  
                    this.saveUrl='api/student/v1/studentlearnstatus/create'
                    this.saveType=this.$http.post
                }
            }
        },
    },

}

</script>